package com.ai.common.gpt;

import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ChatroomUtil {

    private static final Map<String, ConcurrentLinkedQueue<String>> USER_MESSAGE_HISTORY = new ConcurrentHashMap<>();

    private static final int QUEUE_MAX_SIZE  = 10;

    /**
     * 添加用户消息
     * @param userId 用户id
     * @param message 消息内容
     * @param type 0问题，1答案
     * @return
     */
    public static boolean addUserMessage(String userId,String message,int type){
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(message)){
            return false;
        }
        ConcurrentLinkedQueue<String> userMessageQueue = USER_MESSAGE_HISTORY.get(userId);
        boolean offer = false;
        if (userMessageQueue == null){
            userMessageQueue = new ConcurrentLinkedQueue<>();
            offer = userMessageQueue.offer("Q:" + message + "\n");
            USER_MESSAGE_HISTORY.put(userId,userMessageQueue);
        }else{
            if (userMessageQueue.size() > QUEUE_MAX_SIZE - 1){
                String poll = userMessageQueue.poll();
                if (StringUtils.isBlank(poll)){
                    return false;
                }
            }
            if (type == 0){
                offer = userMessageQueue.offer("Q:" + message + "\n");
            }else if (type == 1){
                if (message.length() > 500){
                    message = message.substring(0,500);
                }
                offer = userMessageQueue.offer("A:" + message + "\n\n\n");
            }
        }
        return offer;
    }

    /**
     *  获取用户消息
     * @param userId
     * @return
     */
    public static String getUserMessage(String userId){
        StringBuilder stringBuilder = new StringBuilder();
        ConcurrentLinkedQueue<String> queue = USER_MESSAGE_HISTORY.get(userId);
        if (queue == null){
            return null;
        }
        for (String str : queue){
            stringBuilder.append(str);
        }
        return stringBuilder.toString();
    }

    /**
     *  删除用户消息
     * @param userId
     * @return
     */
    public static void deleteUserMessage(String userId){
        ConcurrentLinkedQueue<String> queue = USER_MESSAGE_HISTORY.get(userId);
        if (queue != null){
            USER_MESSAGE_HISTORY.remove(userId);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            ChatroomUtil.addUserMessage("aaa", i + "", i % 2);
            System.out.println(ChatroomUtil.getUserMessage("aaa"));
        }
        deleteUserMessage("aaa");
        System.out.println("----------------------");
        System.out.println(USER_MESSAGE_HISTORY.get("aaa"));
    }
}
